{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## 01.文件的基本操作"
   ]
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 1.1 操作文件的套路"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# 在 计算机 中要操作文件的套路非常固定，一共包含三个步骤：\n",
    "# 1 打开文件\n",
    "# 2 读、写文件\n",
    "# – 读 将文件内容读入内存\n",
    "# – 写 将内存内容写入文件\n",
    "# 3 关闭文件"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 1.2 操作文件的函数"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# open 打开文件，并且返回文件操作对象\n",
    "# read 将文件内容读取到内存\n",
    "# write 将指定内容写入文件\n",
    "# close 关闭文件\n",
    "# • open 函数负责打开文件，并且返回文件对象\n",
    "# • read/write/close 三个方法都需要通过 文件对象 来调用"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 1.3 read--读取文件"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# • open 函数的第一个参数是要打开的文件名（文件名区分大小写）\n",
    "# – 如果文件 存在，返回 文件操作对象\n",
    "# – 如果文件 不存在，会 抛出异常\n",
    "# • read 方法可以一次性 读入 并 返回 文件的 所有内容\n",
    "# • close 方法负责 关闭文件\n",
    "# – 如果 忘记关闭文件，会造成系统资源消耗，而且会影响到后续对文件的访问\n",
    "# • 注意：read 方法执行后，会把 文件指针 移动到 文件的末尾"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我很开心能继续深造\n"
     ]
    }
   ],
   "source": [
    "file = open(\"README\", encoding='utf-8')\n",
    "\n",
    "text = file.read()\n",
    "print(text)\n",
    "\n",
    "file.close()\n",
    "\n",
    "# 第一次读取之后，文件指针移动到了文件末尾，再次调用不会读取到任何的内容"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "I/O operation on closed file.",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mValueError\u001B[0m                                Traceback (most recent call last)",
      "Input \u001B[1;32mIn [5]\u001B[0m, in \u001B[0;36m<cell line: 1>\u001B[1;34m()\u001B[0m\n\u001B[1;32m----> 1\u001B[0m text \u001B[38;5;241m=\u001B[39m \u001B[43mfile\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mread\u001B[49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m      2\u001B[0m \u001B[38;5;28mprint\u001B[39m(text)\n\u001B[0;32m      4\u001B[0m file\u001B[38;5;241m.\u001B[39mclose()\n",
      "\u001B[1;31mValueError\u001B[0m: I/O operation on closed file."
     ]
    }
   ],
   "source": [
    "# 第一次读取之后，文件指针移动到了文件末尾，再次调用不会读取到任何的内容\n",
    "text = file.read()\n",
    "print(text)\n",
    "\n",
    "file.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello python!\n",
      "今天天气真好"
     ]
    }
   ],
   "source": [
    "# 按行读取文件内容\n",
    "\n",
    "file = open(\"README\", \"r\")\n",
    "\n",
    "while True:\n",
    "    # 读取一行内容\n",
    "    text = file.readline()  # size 参数代表要读取的文件内容大小\n",
    "\n",
    "    # 判断是否读到内容\n",
    "    if not text:\n",
    "        break\n",
    "\n",
    "    # 每读取一行的末尾已经有一个'\\n'\n",
    "    print(text, end=\"\")\n",
    "\n",
    "file.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 1.4 open"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# • open 函数默认以 只读方式 打开文件，并且返回文件对象\n",
    "# 语法如下：\n",
    "# f = open(\"文件名\", \"访问方式\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# 访问方式\n",
    "# r 以只读方式打开文件。文件的指针将会放在文件的开头，这是默认模式。如果文件不存在，抛出异常\n",
    "# rb 打开一个二进制文件，只允许读数据。（若文件不存在，则报错）\n",
    "# w 打开或新建一个文本文件，只允许写数据。（若文件不存在，则创建；若文件存在且含有内容，则先清空后写入）\n",
    "# wb 打开或新建一个二进制文件，只允许写数据。（若文件不存在，则创建；若文件存在且含有内容，则先清空后写入）\n",
    "# r+ 打开一个文本文件，允许读和写。（若文件不存在，则报错；若文件存在且含有内容，则先清空后写入）\n",
    "# rb+ 打开一个二进制文件，允许读和写。（若文件不存在，则报错；若文件存在且含有内容，则先清空后写入）\n",
    "# w+ 打开或新建一个文本文件，允许读和写。（若文件不存在，则创建；若文件存在且含有内容，则先清空后写入）\n",
    "# wb+\n",
    "# a+ 打开一个文本文件，允许读和在文末写数据。（若文件不存在，则创建；若文件存在且含有内容，则在后面追加)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [],
   "source": [
    "f = open(\"README\", \"w\")\n",
    "\n",
    "f.write(\"hello python!\\n\")\n",
    "f.write(\"今天天气真好\")\n",
    "\n",
    "f.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 1.5 文件读写案例 —— 复制文件"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# 用代码的方式，来实现文件复制过程"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "outputs": [],
   "source": [
    "# 小文件复制\n",
    "\n",
    "file_read = open(\"README\")\n",
    "file_write = open(\"README[复件]\", \"w\")\n",
    "\n",
    "text = file_read.read()\n",
    "file_write.write(text)\n",
    "\n",
    "file_read.close()\n",
    "file_write.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [],
   "source": [
    "# 大文件复制\n",
    "\n",
    "file_read = open(\"README\")\n",
    "file_write = open(\"README[复件2]\", \"w\")\n",
    "\n",
    "while True:\n",
    "    text = file_read.readline()\n",
    "\n",
    "    if not text:\n",
    "        break\n",
    "\n",
    "    file_write.write(text)\n",
    "\n",
    "file_read.close()\n",
    "file_write.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 1.6 seek"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# 文件指针定位之 seek 方法\n",
    "# seek(offset, from)\n",
    "# offset ：文件指针偏移量(很多博客在这里将 offset 定义为指针偏移量，但是目前我的看法是这里定义为指针的相对位置)\n",
    "# from ： 0-文件开头 1-当前位置 2-文件末尾(这里的 0,1,2 只是代表了文件位置，而不是说 0,1,2 可以参与指针偏移的计算。from 是可选项，默认为 0.)\n",
    "# 二进制模式下才可以往前偏，二进制模式下 offset 才能为负值"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class '_io.TextIOWrapper'>\n",
      "3 hello\n"
     ]
    }
   ],
   "source": [
    "file = open(\"README\", \"w+\")\n",
    "print(type(file))\n",
    "\n",
    "file.write(\"123 hello\")\n",
    "file.seek(2)\n",
    "\n",
    "text = file.read()\n",
    "print(text)\n",
    "\n",
    "file.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 02.文件/目录的常用管理操作"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "# 需要导入os模块\n",
    "import os"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 2.1 文件操作"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# rename 重命名文件 os.rename(源文件名, 目标文件名)\n",
    "# remove 删除文件,不能删除文件夹\n",
    "# os.remove(文件名)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": [
    "os.rename(\"README\", \"READ\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [],
   "source": [
    "os.remove(\"README[复件2]\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 2.2 目录操作"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "data": {
      "text/plain": "['01 面向对象基本概念.ipynb',\n '02 类和对象.ipynb',\n '03 基本语法.ipynb',\n '04 封装.ipynb',\n '05 私有属性和私有方法.ipynb',\n '06 继承.ipynb',\n '07 多态.ipynb',\n '08 类属性和类方法.ipynb',\n '09 单例.ipynb',\n '10 异常.ipynb',\n '11 模块和包',\n '12 文件']"
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# listdir 目录列表 os.listdir(目录名)\n",
    "# mkdir 创建目录 os.mkdir(目录名)\n",
    "# rmdir 删除目录 os.rmdir(目录名)\n",
    "# getcwd 获取当前目录 os.getcwd()\n",
    "# chdir 修改工作目录 os.chdir(目标目录)\n",
    "# path.isdir 判断是否是文件夹 os.path.isdir(文件路径)\n",
    "\n",
    "os.listdir('..')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [],
   "source": [
    "os.mkdir('./练习目录')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [],
   "source": [
    "os.rmdir(\"练习目录\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [
    {
     "data": {
      "text/plain": "'E:\\\\gitee\\\\python-fundamentals\\\\4 oop\\\\12 文件'"
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "os.getcwd()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [],
   "source": [
    "os.chdir(\".\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [],
   "source": [
    "def dir_dfs(path, width):\n",
    "    file_list = os.listdir(path)\n",
    "    for filename in file_list:  # 遍历当前目录下的所有文件\n",
    "        print(' ' * width + filename)\n",
    "        if os.path.isdir(path + '/' + filename):\n",
    "            dir_dfs(path + '/' + filename, width + 4)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " 01 面向对象基本概念.ipynb\n",
      " 02 类和对象.ipynb\n",
      " 03 基本语法.ipynb\n",
      " 04 封装.ipynb\n",
      " 05 私有属性和私有方法.ipynb\n",
      " 06 继承.ipynb\n",
      " 07 多态.ipynb\n",
      " 08 类属性和类方法.ipynb\n",
      " 09 单例.ipynb\n",
      " 10 异常.ipynb\n",
      " 11 模块和包\n",
      "     .idea\n",
      "         .gitignore\n",
      "         11 模块和包.iml\n",
      "         deployment.xml\n",
      "         inspectionProfiles\n",
      "             profiles_settings.xml\n",
      "             Project_Default.xml\n",
      "         misc.xml\n",
      "         modules.xml\n",
      "         vcs.xml\n",
      "         workspace.xml\n",
      "     11 模块和包.ipynb\n",
      "     wd_01.py\n",
      "     wd_message\n",
      "         receive_message.py\n",
      "         send_message.py\n",
      "         __init__.py\n",
      "         __pycache__\n",
      "             receive_message.cpython-39.pyc\n",
      "             send_message.cpython-39.pyc\n",
      "             __init__.cpython-39.pyc\n",
      " 12 文件\n",
      "     READ\n",
      "     README[复件]\n",
      "     __init__.py\n",
      "     文件.ipynb\n"
     ]
    }
   ],
   "source": [
    "dir_dfs('.', 1)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "outputs": [],
   "source": [
    "def dir_dfs(path, width=1):\n",
    "    file_list = os.listdir(path)\n",
    "    for filename in file_list:\n",
    "        print(' ' * width + filename)\n",
    "        if os.path.isdir(path + '/' + filename):\n",
    "            dir_dfs(path + '/' +filename,width+4)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " 01 面向对象基本概念.ipynb\n",
      " 02 类和对象.ipynb\n",
      " 03 基本语法.ipynb\n",
      " 04 封装.ipynb\n",
      " 05 私有属性和私有方法.ipynb\n",
      " 06 继承.ipynb\n",
      " 07 多态.ipynb\n",
      " 08 类属性和类方法.ipynb\n",
      " 09 单例.ipynb\n",
      " 10 异常.ipynb\n",
      " 11 模块和包\n",
      "     .idea\n",
      "         .gitignore\n",
      "         11 模块和包.iml\n",
      "         deployment.xml\n",
      "         inspectionProfiles\n",
      "             profiles_settings.xml\n",
      "             Project_Default.xml\n",
      "         misc.xml\n",
      "         modules.xml\n",
      "         vcs.xml\n",
      "         workspace.xml\n",
      "     11 模块和包.ipynb\n",
      "     wd_01.py\n",
      "     wd_message\n",
      "         receive_message.py\n",
      "         send_message.py\n",
      "         __init__.py\n",
      "         __pycache__\n",
      "             receive_message.cpython-39.pyc\n",
      "             send_message.cpython-39.pyc\n",
      "             __init__.cpython-39.pyc\n",
      " 12 文件\n",
      "     READ\n",
      "     README[复件]\n",
      "     __init__.py\n",
      "     文件.ipynb\n"
     ]
    }
   ],
   "source": [
    "dir_dfs('.')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}